package com.free.bsf.core.util;

import com.free.bsf.core.config.CoreProperties;
import lombok.val;

import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Date;

/**
 * @Classname DateUtils
 * @Description TODO
 * @Date 2021/4/14 19:58
 * @Created by chejiangyi
 */
public class DateUtils {
    public static Date localDate2Date(LocalDate localDate) {
        if (null == localDate) {
            return null;
        }
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }

    public static LocalDate date2LocalDate(Date date) {
        if(null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        if(localDateTime==null)
            return null;
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    public static LocalDateTime date2LocalDateTime(Date date) {
        if(date==null){
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
    public static Date strToDate(String str,String defaultFormat) {
        if(defaultFormat!=null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(defaultFormat);
                return sdf.parse(str);
            } catch (Exception e) {
            }
        }
        for (val format : PropertyUtils.getPropertyCache(CoreProperties.BsfConvertDateFormat,
                "yyyy-MM-dd HH:mm:ss,yyyy-MM-dd'T'HH:mm:ss,yyyy-MM-dd,yyyyMMddHHmmss").split(",")) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                return sdf.parse(str);
            } catch (Exception e) {
            }
        }
        return null;
    }
}
